package com.yc.sole.system.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import com.yc.sole.system.dto.CacheDto;
import com.yc.sole.system.entity.Cache;
import com.yc.sole.system.mapper.CacheMapper;
import com.yc.sole.system.request.CacheQueryReq;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Objects;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2023-05-26
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class CacheRepository extends ServiceImpl<CacheMapper, Cache> {

    /**
     * 新增
     *
     * @param cacheDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCache(CacheDto cacheDto) {
        Cache entity = new Cache();
        BeanUtil.copyProperties(cacheDto, entity);
        this.save(entity);
    }

    /**
     * 通过Id修改
     *
     * @param cacheDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCacheById(CacheDto cacheDto) {
        Cache entity = new Cache();
        BeanUtil.copyProperties(cacheDto, entity);
        this.updateById(entity);
    }

    /**
     * 通过id删除
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCacheByIds(Collection<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 根据id查询
     *
     * @param cacheId
     * @return
     */
    public CacheDto selectByCacheId(Long cacheId) {
        return BeanUtil.copyProperties(this.getById(cacheId), CacheDto.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @return RestResult
     */
    public Paging<CacheDto> selectCachePage(Paging page, CacheQueryReq cacheQueryReq) {
        LambdaQueryWrapper<Cache> queryWrapper = Wrappers.<Cache>lambdaQuery()
                .like(CharSequenceUtil.isNotBlank(cacheQueryReq.getCacheCode()), Cache::getCacheCode, cacheQueryReq.getCacheCode())
                .eq(Objects.nonNull(cacheQueryReq.getCacheType()), Cache::getCacheType, cacheQueryReq.getCacheType())
                .orderByDesc(Cache::getId);
        return PageUtil.pageCopy(this.page(PageUtil.toMybatisPage(page), queryWrapper), CacheDto.class);
    }
}
